package main

import (
	"context"
	"fmt"
	"github.com/olivere/elastic/v7"
)

var (
	// 索引名称
	indexName = "your_index"
	//indexName = "your_index_new"
	// 索引映射
	mapping = `{
		"mappings":{
			"dynamic": "strict",
			"properties":{
			"id": { "type": "long" },
			"username": { "type": "keyword" },
			"nickname": { "type": "text" },
			"phone": { "type": "keyword" },
			"age": { "type": "integer" },
			"ancestral": { "type": "text" },
			"identity": { "type": "text" },
			"update_time": { "type": "long" },
			"create_time": { "type": "long" }
			}
		},
		"settings" : {
			"index" : {
				"number_of_shards" : "1",
				"number_of_replicas" : "1"
			}
		}
	}`
)

func main() {
	// 创建ElasticSearch客户端
	client, err := elastic.NewClient(
		elastic.SetURL("http://162.14.70.254:9200"),
		elastic.SetSniff(false))
	if err != nil {
		panic(err)
	}
	// 输出client
	fmt.Println("hello world", client)

	// 创建索引
	//exists, err := client.CreateIndex(indexName).BodyString(mapping).Do(context.Background())
	//if err != nil {
	//	panic(err)
	//}
	//fmt.Println("创建索引成功", exists)
	//删除索引
	//exists, err := client.DeleteIndex(indexName).Do(context.Background())
	//if err != nil {
	//	panic(err)
	//	return
	//}
	//fmt.Println("删除索引成功", exists)

	// 迁移索引
	// 迁移的是索引的配置和数据
	targetIndex := "your_index_new"
	resp, err := client.Reindex().SourceIndex(indexName).DestinationIndex(targetIndex).Do(context.Background())
	if err != nil {
		panic(err)
		return
	}
	fmt.Println("迁移索引成功", resp)

	// 查询索引
	//searchResult, err := client.Search().Index(indexName).Query(elastic.NewMatchAllQuery()).Do(context.Background())
	//if err != nil {
	//	panic(err)
	//}
	//
	//if searchResult.Hits.TotalHits.Value > 0 {
	//	fmt.Printf("查询到%d条数据\n", searchResult.Hits.TotalHits.Value)
	//	for _, hit := range searchResult.Hits.Hits {
	//		fmt.Printf("Document ID: %s, Score: %.3f, Source: %s", hit.Id, hit.Score, hit.Source)
	//	}
	//} else {
	//	fmt.Println("未查询到索引index的数据文档")
	//}
}
